package com.taijihuabao.modules.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.taijihuabao.common.commonutils.BusinessIdUtil;
import com.taijihuabao.common.commonutils.PageResult;
import com.taijihuabao.common.redisconfig.UserLoad;
import com.taijihuabao.modules.entity.*;
import com.taijihuabao.modules.enums.optenums.approval.ApprovalStatusEnum;
import com.taijihuabao.modules.enums.optenums.approval.BusinessEnum;
import com.taijihuabao.modules.mapper.*;
import com.taijihuabao.modules.model.approval.dto.ApprovalProcessDTO;
import com.taijihuabao.modules.model.approval.dto.ApproveCompleteDTO;
import com.taijihuabao.modules.model.approval.vo.ApplyVO;
import com.taijihuabao.modules.model.approval.vo.ApprovalVO;
import com.taijihuabao.modules.model.quit.dto.QuitDTO;
import com.taijihuabao.modules.service.ApprovalProcessService;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author wang
 */
@Service
public class QuitApprovalProcessServiceImpl implements ApprovalProcessService {

    @Autowired
    RuntimeService runtimeService;
    @Autowired
    TaskService taskService;
    @Autowired
    RepositoryService repositoryService;
    @Resource
    QuitBusinessMapper quitBusinessMapper;
    @Resource
    ApprovalBusinessMapper approvalBusinessMapper;
    @Resource
    QuitBusinessHistoryMapper quitBusinessHistoryMapper;
    @Resource
    DeptUserMapper deptUserMapper;
    @Resource
    ApprovalMapper approvalMapper;
    @Resource
    ApprovalHistoryMapper approvalHistoryMapper;

    /**
     * 审核通过或不通过
     */
    private final int PASS = 1;
    private final int REJECT = 2;

    /**
     * 完成任务
     * @param approveCompleteDTO
     */
    @Override
    public void completeTask(ApproveCompleteDTO approveCompleteDTO) {
        Long userId = UserLoad.getUser().getId();
        //任务id
        String taskId = approveCompleteDTO.getTaskId();
        //领取任务
        taskService.claim(taskId, String.valueOf(userId));
        // 查询当前任务对象
        Task task = ProcessEngines.getDefaultProcessEngine().getTaskService()
                .createTaskQuery().taskId(taskId).singleResult();
        //获取审批单
        String businessKey = task.getBusinessKey();
        ApprovalEntity approval = approvalMapper.selectById(Long.valueOf(businessKey));
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByUserId(userId);
        String deptCode = deptUserEntities.get(0).getDeptCode();
        //审批历史
        ApprovalHistoryEntity approvalHistoryEntity = new ApprovalHistoryEntity();
        approvalHistoryEntity.setApprovalType(approval.getApprovalType());
        approvalHistoryEntity.setApprovalCode(approval.getApprovalCode());
        approvalHistoryEntity.setApplyUserId(approval.getApplyUserId());
        approvalHistoryEntity.setApplyDeptCode(approval.getApplyDeptCode());
        approvalHistoryEntity.setApplyName(approval.getApplyName());
        approvalHistoryEntity.setApprovalOpinion(approveCompleteDTO.getApprovalOpinion());
        approvalHistoryEntity.setApprovalTask(approveCompleteDTO.getTaskId());
        approvalHistoryEntity.setApprovalUserId(userId);
        approvalHistoryEntity.setApprovalDeptCode(deptCode);
        approvalHistoryEntity.setApprovalFlow(task.getName());
        if (PASS == (approveCompleteDTO.getAgree())) {
            approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
        }
        if (REJECT == (approveCompleteDTO.getAgree())) {
            approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("thisDept", approveCompleteDTO.getAgree());
        if (PASS == (approveCompleteDTO.getAgree())) {
            approval.setApprovalState(ApprovalStatusEnum.STATE_ING.getCode());
        }
        if (REJECT == (approveCompleteDTO.getAgree())) {
            approval.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
        }
        String perApp = "人事主管";
        if (perApp.equals(task.getName())) {
            map.put("perManager", approveCompleteDTO.getAgree());
            map.remove("thisDept");
            if (PASS == (approveCompleteDTO.getAgree())) {
                approval.setApprovalState(ApprovalStatusEnum.STATE_ING.getCode());
            }
            if (REJECT == (approveCompleteDTO.getAgree())) {
                approval.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
            }
        }
        String topApp = "总经理";
        if (topApp.equals(task.getName())) {
            map.put("genManager", approveCompleteDTO.getAgree());
            map.remove("thisDept");
            if (PASS == (approveCompleteDTO.getAgree())) {
                approval.setApprovalState(ApprovalStatusEnum.STATE_ING.getCode());
            }
            if (REJECT == (approveCompleteDTO.getAgree())) {
                approval.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
            }
        }
        String checkApp = "考勤专员";
        if (checkApp.equals(task.getName())) {
            map.put("checkWork", approveCompleteDTO.getAgree());
            map.remove("thisDept");
            if (PASS == (approveCompleteDTO.getAgree())) {
                approval.setApprovalState(ApprovalStatusEnum.STATE_ING.getCode());
            }
            if (REJECT == (approveCompleteDTO.getAgree())) {
                approval.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
            }
        }
        String perWorkApp = "人事专员";
        if (perWorkApp.equals(task.getName())) {
            approval.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
        }
        approval.setApprovalUserId(userId);
        approval.setApprovalDeptCode(deptCode);
        approval.setApprovalOpinion(approveCompleteDTO.getApprovalOpinion());
        approval.setApprovalTask(taskId);
        //修改审批数据
        approvalMapper.updateApproval(approval);
        //完成任务时添加节点历史数据
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
        taskService.complete(taskId, map);
    }

    /**
     * 查询待办任务
     * @param processName
     * @return
     */
    @Override
    public List<ApprovalVO> findTask(String processName) {
        List<Task> result = taskService.createTaskQuery()
                .processDefinitionKey(processName)
                .taskCandidateUser(String.valueOf(UserLoad.getUser().getId()))
                .list();
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        List<ApprovalVO> taskInfo = new ArrayList<>();
        for (Task task : result) {
            String businessKey = task.getBusinessKey();
            ApprovalEntity approvalEntity = approvalMapper.selectById(Long.valueOf(businessKey));
            if (!Objects.isNull(approvalEntity)) {
                //返回给前端的数据
                ApprovalVO approvalVO = approvalMapper.selectByApprovalCode(approvalEntity.getApprovalCode());
                approvalVO.setApprovalTask(task.getId());
                //添加业务从表的数据
                QuitBusinessEntity quitBusinessEntity = quitBusinessMapper.selectByQuitId(approvalVO.getApplyCode());
                if(!Objects.isNull(quitBusinessEntity)) {
                    ApplyVO applyVO = new ApplyVO();
                    applyVO.setApplyRemarks(approvalVO.getApplyRemarks());
                    applyVO.setApplyContent(approvalVO.getApplyContent());
                    applyVO.setApplyPosition(quitBusinessEntity.getQuitPosition());
                    applyVO.setDirectLeader(quitBusinessEntity.getDirectLeader());
                    applyVO.setWhetherInterview(quitBusinessEntity.getWhetherInterview());
                    applyVO.setQuitDate(quitBusinessEntity.getQuitDate());
                    approvalVO.setApplyVO(applyVO);
                }
                taskInfo.add(approvalVO);
            }
        }
        return taskInfo;
    }

    /**
     * 用户查询自己已审批的任务
     * @param processName
     * @return
     */
    @Override
    public List<ApprovalVO> findCompleteTask(String processName) {
        Long userId = UserLoad.getUser().getId();
        List<ApprovalVO> approvalVOS = approvalHistoryMapper.selectByApprovalUserId(userId);
        if (!CollectionUtils.isEmpty(approvalVOS)) {
            for (int i = 0;i<approvalVOS.size();i++){
                String quitApproval = approvalVOS.get(i).getApprovalCode().substring(0,4);
                if (BusinessEnum.QUIT.getCode().equals(quitApproval)){
                    ApprovalBusinessEntity approvalBusinessEntity =
                            approvalBusinessMapper.selectOne(approvalVOS.get(i).getApprovalCode());
                    QuitBusinessEntity quitBusinessEntity =
                            quitBusinessMapper.selectByQuitId(approvalBusinessEntity.getBusinessId());
                    if(!Objects.isNull(quitBusinessEntity)){
                        ApplyVO applyVO = new ApplyVO();
                        applyVO.setApplyContent(approvalBusinessEntity.getApplyContent());
                        applyVO.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
                        applyVO.setApplyPosition(quitBusinessEntity.getQuitPosition());
                        applyVO.setDirectLeader(quitBusinessEntity.getDirectLeader());
                        applyVO.setWhetherInterview(quitBusinessEntity.getWhetherInterview());
                        applyVO.setQuitDate(quitBusinessEntity.getQuitDate());
                        approvalVOS.get(i).setApplyVO(applyVO);
                    }
                }else {
                    approvalVOS.remove(approvalVOS.get(i));
                    i--;
                }
            }
        }
        return approvalVOS;
    }

    /**
     * 审批退回后，修改
     * @param approvalProcessDTO
     * @return String
     */
    @Override
    public String reSubmit(ApprovalProcessDTO approvalProcessDTO) {
        //将前台接受的json字符串转化成自己想要的实体
        QuitDTO quitDTO =
                JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), QuitDTO.class);
        Long userId = UserLoad.getUser().getId();
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByUserId(userId);
        String deptCode = deptUserEntities.get(0).getDeptCode();
        // 查询当前任务对象
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(approvalProcessDTO.getProcessName())
                .taskCandidateUser(String.valueOf(userId))
                .list();
        //获取审批单
        String businessKey = taskList.get(0).getBusinessKey();
        ApprovalEntity approval = approvalMapper.selectById(Long.valueOf(businessKey));

        //修改审批单
        approval.setApprovalType(quitDTO.getApplyType());
        approval.setApprovalUserId(userId);
        approval.setApprovalState(ApprovalStatusEnum.STATE_ING.getCode());
        approval.setApprovalOpinion(null);
        approval.setApprovalDeptCode(deptCode);
        approval.setApprovalTask(taskList.get(0).getId());
        approvalMapper.updateApproval(approval);
        //修改业务主表
        ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approval.getApprovalCode());
        approvalBusinessEntity.setApplyContent(quitDTO.getApplyContent());
        approvalBusinessEntity.setApplyRemarks(quitDTO.getApplyRemarks());
        approvalBusinessEntity.setApplyType(quitDTO.getApplyType());
        approvalBusinessMapper.updateApprovalBusiness(approvalBusinessEntity);
        //修改业务从表单
        QuitBusinessEntity quit = quitBusinessMapper.selectByQuitId(approvalBusinessEntity.getApplyCode());
        quit.setQuitPosition(quitDTO.getQuitPosition());
        quit.setDirectLeader(quitDTO.getDirectLeader());
        quit.setWhetherInterview(quitDTO.getWhetherInterview());
        quit.setQuitDate(quitDTO.getQuitDate());
        quitBusinessMapper.updateQuit(quit);
        //新增业务历史数据
        QuitBusinessHistoryEntity quitBusinessHistoryEntity = new QuitBusinessHistoryEntity();
        quitBusinessHistoryEntity.setBusinessId(approvalBusinessEntity.getBusinessId());
        quitBusinessHistoryEntity.setApplyType(quitDTO.getApplyType());
        quitBusinessHistoryEntity.setApplyRemarks(quitDTO.getApplyRemarks());
        quitBusinessHistoryEntity.setApplyContent(quitDTO.getApplyContent());
        quitBusinessHistoryEntity.setQuitPosition(quitDTO.getQuitPosition());
        quitBusinessHistoryEntity.setDirectLeader(quit.getDirectLeader());
        quitBusinessHistoryEntity.setWhetherInterview(quit.getWhetherInterview());
        quitBusinessHistoryEntity.setQuitDate(quitDTO.getQuitDate());
        quitBusinessHistoryMapper.insertQuitBusinessHistory(quitBusinessHistoryEntity);
        //新增审批节点历史数据
        ApprovalHistoryEntity approvalHistoryEntity = new ApprovalHistoryEntity();
        approvalHistoryEntity.setApprovalType(approval.getApprovalType());
        approvalHistoryEntity.setApprovalCode(approval.getApprovalCode());
        approvalHistoryEntity.setApplyUserId(approval.getApplyUserId());
        approvalHistoryEntity.setApplyDeptCode(approval.getApplyDeptCode());
        approvalHistoryEntity.setApplyName(approval.getApplyName());
        approvalHistoryEntity.setApprovalOpinion(null);
        approvalHistoryEntity.setApprovalTask(taskList.get(0).getId());
        approvalHistoryEntity.setApprovalUserId(userId);
        approvalHistoryEntity.setApprovalDeptCode(deptCode);
        approvalHistoryEntity.setApprovalFlow(taskList.get(0).getName());
        approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);

        //完成任务
        taskService.claim(taskList.get(0).getId(), String.valueOf(userId));
        taskService.complete(taskList.get(0).getId());
        return approval.getApprovalCode();
    }

    @Override
    public PageResult<T> selectByApplyUserId(int page, int size) {
        PageHelper.startPage(page, size);
        Long userId = UserLoad.getUser().getId();
        List<ApprovalVO> approvalVOList = approvalMapper.selectByApplyUserId(userId);
        List<ApprovalVO> quitApprovalList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(approvalVOList)) {
            for (ApprovalVO approvalVO : approvalVOList) {
                //筛选离职审批单
                if (approvalVO.getApprovalCode().contains(BusinessEnum.QUIT.getCode())) {
                    QuitBusinessEntity quitBusinessEntity = quitBusinessMapper.selectByQuitId(approvalVO.getApprovalCode());
                    if (!Objects.isNull(quitBusinessEntity)) {
                        ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalVO.getApprovalCode());
                        approvalVO.setApplyContent(approvalBusinessEntity.getApplyContent());
                        approvalVO.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
                        approvalVO.setApplyPosition(quitBusinessEntity.getQuitPosition());
                        approvalVO.setDirectLeader(quitBusinessEntity.getDirectLeader());
                        approvalVO.setQuitDate(quitBusinessEntity.getQuitDate());
                        approvalVO.setWhetherInterview(quitBusinessEntity.getWhetherInterview());
                        quitApprovalList.add(approvalVO);
                    }
                }
            }
        }
        return new PageResult(quitApprovalList);
    }

    @Override
    public ApprovalVO selectByApprovalCode(String approvalCode) {
        ApprovalVO approval = approvalMapper.selectByApprovalCode(approvalCode);
        if(!Objects.isNull(approval)){
            QuitBusinessEntity quitBusinessEntity = quitBusinessMapper.selectByQuitId(approvalCode);
            if(!Objects.isNull(quitBusinessEntity)){
                approval.setApplyPosition(quitBusinessEntity.getQuitPosition());
                approval.setDirectLeader(quitBusinessEntity.getDirectLeader());
                approval.setQuitDate(quitBusinessEntity.getQuitDate());
                approval.setWhetherInterview(quitBusinessEntity.getWhetherInterview());
            }
        }
        return approval;
    }

    @Override
    public List<ApprovalVO> findActivities(String approvalCode) {
        List<ApprovalVO> approvals = approvalHistoryMapper.selectByApprovalCode(approvalCode);
        if(!CollectionUtils.isEmpty(approvals)){
            approvals.remove(approvals.get(0));
            for(ApprovalVO approvalVO : approvals){
                ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalCode);
                QuitBusinessEntity quitBusinessEntity = quitBusinessMapper.selectByQuitId(approvalBusinessEntity.getApplyCode());
                ApplyVO applyVO = new ApplyVO();
                applyVO.setApplyContent(approvalBusinessEntity.getApplyContent());
                applyVO.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
                applyVO.setApplyPosition(quitBusinessEntity.getQuitPosition());
                applyVO.setDirectLeader(quitBusinessEntity.getDirectLeader());
                applyVO.setWhetherInterview(quitBusinessEntity.getWhetherInterview());
                applyVO.setQuitDate(quitBusinessEntity.getQuitDate());
                approvalVO.setApplyVO(applyVO);
            }
        }
        return approvals;
    }

    /**
     * 启动流程
     * @param approvalProcessDTO
     */
    @Override
    public String startProcess(ApprovalProcessDTO approvalProcessDTO) {
        //将前台接受的json字符串转化成自己想要的实体
        QuitDTO quitDTO =
                JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), QuitDTO.class);
        //传入的processName对应key
        String key = approvalProcessDTO.getProcessName();
        //业务从表实体
        QuitBusinessEntity quitBusinessEntity = new QuitBusinessEntity();
        //获取业务主键
        String businessId = BusinessIdUtil.createBusinessId(key);
        quitBusinessEntity.setQuitId(businessId);
        quitBusinessEntity.setQuitDate(quitDTO.getQuitDate());
        quitBusinessEntity.setQuitPosition(quitDTO.getQuitPosition());
        quitBusinessEntity.setDirectLeader(quitDTO.getDirectLeader());
        quitBusinessEntity.setWhetherInterview(quitDTO.getWhetherInterview());
        quitBusinessMapper.insertQuit(quitBusinessEntity);

        //业务主表实体
        ApprovalBusinessEntity approvalBusinessEntity = new ApprovalBusinessEntity();
        approvalBusinessEntity.setBusinessId(businessId);
        approvalBusinessEntity.setApplyType(quitDTO.getApplyType());
        approvalBusinessEntity.setApplyCode(quitBusinessEntity.getQuitId());
        approvalBusinessEntity.setApplyRemarks(quitDTO.getApplyRemarks());
        approvalBusinessEntity.setApplyContent(quitDTO.getApplyContent());
        approvalBusinessMapper.insertApprovalBusiness(approvalBusinessEntity);

        //业务历史
        QuitBusinessHistoryEntity quitBusinessHistoryEntity = new QuitBusinessHistoryEntity();
        quitBusinessHistoryEntity.setBusinessId(approvalBusinessEntity.getBusinessId());
        quitBusinessHistoryEntity.setApplyType(approvalBusinessEntity.getApplyType());
        quitBusinessHistoryEntity.setQuitPosition(quitBusinessEntity.getQuitPosition());
        quitBusinessHistoryEntity.setDirectLeader(quitBusinessEntity.getDirectLeader());
        quitBusinessHistoryEntity.setWhetherInterview(quitBusinessEntity.getWhetherInterview());
        quitBusinessHistoryEntity.setQuitDate(quitBusinessEntity.getQuitDate());
        quitBusinessHistoryEntity.setApplyContent(approvalBusinessEntity.getApplyContent());
        quitBusinessHistoryEntity.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
        quitBusinessHistoryMapper.insertQuitBusinessHistory(quitBusinessHistoryEntity);

        //登录用户id、name、部门编号
        Long userId = UserLoad.getUser().getId();
        String name = UserLoad.getUser().getName();
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByUserId(userId);
        String deptCode = deptUserEntities.get(0).getDeptCode();
        //工作流表实体
        ApprovalEntity approvalEntity = new ApprovalEntity();
        approvalEntity.setApprovalType(quitDTO.getApplyType());
        approvalEntity.setApprovalCode(approvalBusinessEntity.getBusinessId());
        approvalEntity.setApplyUserId(userId);
        approvalEntity.setApplyName(name);
        approvalEntity.setApplyDeptCode(deptCode);
        approvalMapper.insertApproval(approvalEntity);

        //启动审批流程
        ProcessInstance processInstance = runtimeService
                .startProcessInstanceByKey(key, String.valueOf(approvalEntity.getId()));
        System.out.println(processInstance);
        //启动成功修改工作流表状态为ing
        approvalMapper.updateApprovalIng(approvalEntity.getId());

        //自动完成修改申请节点
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(key)
                .processInstanceBusinessKey(String.valueOf(approvalEntity.getId()))
                .list();
        String task = taskList.get(0).getId();
        String taskName = taskList.get(0).getName();
        //第一个节点自动通过添加一条历史数据
        ApprovalHistoryEntity approvalHistoryEntity = new ApprovalHistoryEntity();
        approvalHistoryEntity.setApprovalType(approvalEntity.getApprovalType());
        approvalHistoryEntity.setApprovalCode(approvalEntity.getApprovalCode());
        approvalHistoryEntity.setApplyUserId(approvalEntity.getApplyUserId());
        approvalHistoryEntity.setApplyName(approvalEntity.getApplyName());
        approvalHistoryEntity.setApplyDeptCode(approvalEntity.getApplyDeptCode());
        approvalHistoryEntity.setApprovalDeptCode(deptCode);
        approvalHistoryEntity.setApprovalTask(task);
        approvalHistoryEntity.setApprovalFlow(taskName);
        approvalHistoryEntity.setApprovalUserId(userId);
        approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
        //拾取任务、完成任务
        taskService.claim(task, String.valueOf(userId));
        taskService.complete(task);
        return approvalEntity.getApprovalCode();
    }

    /**
     * 部署流程
     */
    @Override
    public void deploy() {
        //部署流程定义并获取流程部署对象
        Deployment deployment = repositoryService
                .createDeployment()
                .name("离职审批流程")
                .addClasspathResource("bpmn/quit.bpmn")
                .addClasspathResource("bpmn/quit.xml")
                .deploy();
        System.out.println("流程部署Id：" + deployment.getId() + "，" +
                "流程部署name：" + deployment.getName());
    }

    /**
     * 返回流程部署的key
     * @return
     */
    @Override
    public String getProcessName() {
        return BusinessEnum.QUIT.getCode();
    }

}
